<?php
namespace Frieza\Modules\Decoration\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\model\Decoration\Tag as mTag;
use Doraemon\service\Decoration\Main as sMain;

class CategoryController extends Controller
{
    const PAGE_SIZE = 500;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }

        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }
            }
        }

        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function list(Request $request,Content $content){
        $request = $request->all();
        $request = self::_filterWhere($request);

        return $content
            ->header('分类列表')
            ->breadcrumb(
                ['text' => '一级分类', 'url' => '/decoration/category']
            )
            ->body(self::listAction($request));
    }

    public function listAction($request = []){
        $category = sMain::getCategory($request);
        $gridModel = new pGridDataModel($category['list'], $category['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('title', '标题')->placeholder('请输入标题');
                });
            });

            $grid->column('id')->sort();
            $grid->column('title', '一级分类');
            $status = [
                'on' => [
                    'value' => mCategory::SHOW_OPEN,
                    'text' => '是'
                ],
                'off' => [
                    'value' => mCategory::SHOW_CLOSE,
                    'text' => '否'
                ],
            ];
            $grid->column('is_show', '显示')->switchToggle($status);
            $grid->column('sons', '二级分类')->display(function () {
                $format = [];
                if ($this->sons) {
                    foreach ($this->sons as &$_son) {
                        $format[] = "<a href='/admin/decoration/category/{$_son['parent_id']}/edit/{$_son['id']}/edit'>{$_son['title']}</a>";
                    }
                }
                return $format;
            })->label('default');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function edit(Request $request,Content $content, $parentId = 0, $sonId = 0){
        $requests = $request->all();
        $requests['parent_id'] = $parentId;
        $requests['id'] = $sonId;
        $requests = self::_filterWhere($requests);

        $tab = new Tab();
        $tab->add('基本信息', self::editAction($requests, strpos($request->url(), 'create')));
        if(!strpos($request->url(), 'create')) {
            if($sonId > 0) {
                $tab->addLink('主题列表', '/admin/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/subject');
            }else{
                $tab->add('子分类列表', self::listAction($requests));
                $tab->addLink('资源位列表', '/admin/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/adv');
            }
        }
        $curUrl = '';
        if($sonId > 0) {
            return $content
                ->header('分类编辑')
                ->breadcrumb(
                    ['text' => '一级分类', 'url' => '/decoration/category'],
                    //['text' => '二级分类', 'url' => $request->url()],
                    ['text' => '分类编辑', 'url' => '/decoration/category/create']
                )
                ->body($tab);
        }else{
            return $content
                ->header('分类编辑')
                ->breadcrumb(
                    ['text' => '一级分类', 'url' => '/decoration/category'],
                    ['text' => '分类编辑', 'url' => '/decoration/category/create']
                )
                ->body($tab);
        }
    }

    public function editAction($request, $isCreate = false){

        $category = mCategory::getAllByWhere(['id' =>$request['AND']['parent_id'], 'status' => mCategory::STATUS_OPEN], ['id', 'title']);
        $categorys = [];
        if (!empty($category)) {
            foreach ($category as &$_v) {
                $categorys[$_v['id']] = $_v['title'];
            }
        }

        $data = [];
        if(!$isCreate) {
            if (!empty($request['AND']['parent_id']) && $request['AND']['parent_id'] > 0) {
                $data = mCategory::getOneByWhere(['id' => $request['AND']['parent_id']]);
            }
            if (!empty($request['AND']['id']) && $request['AND']['id'] > 0) {
                $data = mCategory::getOneByWhere(['id' => $request['AND']['id']]);
            }
        }

        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        if (!empty($categorys)) {
            $form->select('parent_id', '上级分类')
                ->options($categorys)
                ->setWidth(4, 2)
                ->default(isset($data['parent_id'])?$data['parent_id']:'')
            ;
        }

        $form->text('title', '标题')->setWidth(4, 2)->required('不能为空');
        $form->radio('is_show', '是否显示')
            ->options([0=>'否', 1=>'是'])
            ->setWidth(4, 2);
        $form->radio('is_cover', '是否需要封面')
            ->options([0=>'否', 1=>'是'])
            ->options([0=>'否', 1=>'是'])
            ->setWidth(4, 2);

        $form->action('/admin/decoration/category/save');

        return $form->render();
    }

    public function show(Request $request, $step, $id){
        $params = $request->all();
        if(isset($params['is_show'] )) {
            if ($params['is_show'] == 'on') {
                $param = [
                    'is_show'=> mCategory::SHOW_OPEN,
                    'admin_id'=>Admin::user()->id,
                ];
            } else {
                $param = [
                    'is_show'=> mCategory::SHOW_CLOSE,
                    'admin_id'=>Admin::user()->id,
                ];
            }
        }else if(isset($params['is_cover'])){
            if ($params['is_cover'] == 'on') {
                $param = [
                    'is_cover'=> mCategory::SHOW_OPEN,
                    'admin_id'=> Admin::user()->id,
                ];
            } else {
                $param = [
                    'is_cover'=> mCategory::SHOW_CLOSE,
                    'admin_id'=>Admin::user()->id,
                ];
            }
        }
        $result = mCategory::updateData($param,['id'=>$id]);
        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function editCategory(Request $request, $categoryId){
        $params = $request->all();
        $params['id'] = $categoryId;
        $param = [
            'is_show' => $params['is_show'] == 'on'? 1: 0,
            'admin_id' => Admin::user()->id,
        ];

        $result = mCategory::updateData($param,['id'=>$params['id']]);
        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "修改成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "修改失败",
            ]);
        }
    }

    public function sort(Request $request){
        $params = $request->all();

        $result = mCategory::action(function()use($params){
            foreach($params['sort'] as $_k=>&$_v){
                if(!mCategory::updateData(['sort' => $_v], ['id' => $_k])){
                    return false;
                }
            }
            return true;
        });

        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }

    }

    public static function save(Request $request, $id = 0)
    {
        $params = $request->all();
        $param = [
            'title' => $params['title'],
            'is_show' => isset($params['is_show']) ? $params['is_show'] : 0,
            'is_cover' => isset($params['is_cover']) ? $params['is_cover'] : 0,
            'parent_id' => isset($params['parent_id']) ? $params['parent_id'] : 0,
            'admin_id' => Admin::user()->id,
        ];

        if(!isset($params['id'])) {
            $param['add_time'] = date('Y-m-d H:i:s');
            $result = mCategory::addData($param);
        }else{
            $result = mCategory::updateData($param,['id'=>$params['id']]);
        }

        if($result){
            sCache::updateCache();

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            return redirect('/admin/decoration/category')->with(compact('success'));
        }else{
            $error = new MessageBag([
                'title' => $result
            ]);

            return back()->with(compact('error'));
        }

    }

    public static function del($parentId = 0 ,$categoryId = 0)
    {
        $data = ['status'=>mCategory::STATUS_DELETE];
        $result = mCategory::updateData($data, ['OR' => ['id' => $categoryId, 'parent_id' => $categoryId]]);

        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

}